import { t } from 'i18next'
import React, { forwardRef, useEffect, useRef, useState } from 'react'
import { useVmpStore } from '../store'
import { StartIcon, StopIcon, StyledWrap } from './style'
import { VmpEntity } from '../interface'
import { useVmpTypeStore } from '../store.get'
import { useManagerStore } from '../../main/manager/store'
import { useMtVmpStore } from '../../mtVmp/store'
import Alert from '@/components/Alert'
import { useUnmountedRef } from 'ahooks'

export interface VmpPopUpProps {
	type: 'vmp' | 'mtVmp'
	editVmp?: () => void
	closePannel: () => void
}
const VmpPopUp = forwardRef((props: VmpPopUpProps, ref: any) => {
	const { type, editVmp, closePannel, ...restProps } = props
	const [state, setState] = useState(0)
	const [name, setName] = useState('')
	const [isInit, setIsInit] = useState(false)
	const unmountedRef = useUnmountedRef()
	const vmpParams = useRef<VmpEntity | null>(null)
	const chairman = useManagerStore((state) => state.chairman)
	useEffect(() => {
		if (type === 'vmp') {
			/**获取接口数据 */
			useVmpStore.getState()._fetchVmpParams((data) => {
				if (!unmountedRef.current) {
					setIsInit(true)
					vmpParams.current = data ?? null
					setState(data?.state ?? 0)
					setName(data?.name ?? '')
				}
			}, reset)
		} else {
			if (chairman && chairman.mtKey) {
				/**管理方存在*/
				useMtVmpStore.getState()._fetchVmpParams((data) => {
					if (!unmountedRef.current) {
						setIsInit(true)
						vmpParams.current = data ?? null
						setState(data ? 1 : 0)
						setName(data?.name ?? '')
					}
				}, reset)
			} else {
				reset()
			}
		}
	}, [])
	const reset = () => {
		setState(0)
		setName('')
	}
	const handleStart = (e: React.MouseEvent) => {
		e.stopPropagation()
		closePannel()
		if (type === 'vmp') {
			let _localStorage_vmpParams = useVmpStore.getState()._getSessionStage() /**缓存数据 */
			if (_localStorage_vmpParams) {
				useVmpStore.getState()._start(_localStorage_vmpParams)
			} else if (vmpParams.current) {
				useVmpStore.getState()._start(vmpParams.current)
			}
		} else {
			if (chairman && chairman.mtKey) {
				if (!chairman.status.isOnline) {
					Alert(t('当前会议管理方已离线'))
					return
				}
				let _localStorage_vmpParams = useMtVmpStore.getState()._getSessionStage() /**缓存数据 */
				if (_localStorage_vmpParams) {
					useMtVmpStore
						.getState()
						._start(_localStorage_vmpParams, { mt_id: chairman.mtid, name: chairman.INITIAL_NAME })
				} else if (vmpParams.current) {
					useMtVmpStore
						.getState()
						._start(vmpParams.current, { mt_id: chairman.mtid, name: chairman.INITIAL_NAME })
				} else {
					const default_data = useMtVmpStore.getState()._getDefaultData()
					useMtVmpStore.getState()._start(default_data, { mt_id: chairman.mtid, name: chairman.INITIAL_NAME })
				}
			} else {
				Alert(t('请设置当前会议管理方。'))
			}
		}
	}
	const handleStop = (e: React.MouseEvent) => {
		e.stopPropagation()
		closePannel()
		if (type === 'vmp') {
			useVmpStore.getState()._stop()
		} else {
			if (chairman) {
				useMtVmpStore.getState()._stop({ mt_key: chairman.mtKey, mt_id: chairman.mtid })
			}
		}
	}
	const openPlanModal = (e: React.MouseEvent) => {
		e.stopPropagation()
		closePannel()
		if (type === 'vmp') {
			useVmpTypeStore.setState({ type: 'vmp' })
			useVmpStore.setState({
				isOpen: false,
				isShowPlanOperateModal: true,
				localStoragePreName: useVmpStore.getState()._getStageName(),
				vmpParamsName: vmpParams.current?.name ?? '',
				vmpState: vmpParams.current?.state ?? 0,
			})
		} else {
			if (chairman && chairman.mtKey) {
				useVmpTypeStore.setState({ type: `mtVmp_${chairman.mtKey}` })
				useMtVmpStore.setState({
					isOpen: false,
					isShowPlanOperateModal: true,
					localStoragePreName: useMtVmpStore.getState()._getStageName(),
					vmpParamsName: vmpParams.current?.name ?? '',
					vmpState: vmpParams.current ? 1 : 0,
				})
			} else {
				Alert(t('请设置当前会议管理方。'))
			}
		}
	}
	return (
		<StyledWrap ref={ref} {...restProps}>
			{isInit ? (
				<div className="content vmp-popup__i18n">
					<div className="btn-wrap line" onClick={state === 0 ? handleStart : handleStop}>
						{state === 0 ? (
							<div className="start-btn-wrap">
								<span>{t('立即开始')}</span>
								<StartIcon className="start-icon" />
							</div>
						) : (
							<div className="stop-btn-wrap">
								<span>{t('立即停止')}</span>
								<StopIcon className="stop-icon" />
							</div>
						)}
						<div className="plan_name">{name ? name : t('默认预案')}</div>
					</div>
					<div className="use-plan-wrap line" onClick={openPlanModal}>
						{t('使用预案')}...
					</div>
					<div className="line edit-vmp" onClick={editVmp}>
						{t('编辑画面合成')}
					</div>
				</div>
			) : (
				<div className="loading-panel"></div>
			)}
		</StyledWrap>
	)
})
export default VmpPopUp
